const express = require('express');
const router = express.Router();
const { Op, Sequelize } = require('sequelize');
const { Order, Product, User, OrderItem } = require('../models');
const auth = require('../middleware/auth');
const adminAuth = require('../middleware/adminAuth');
const logger = require('../utils/logger');
const qrCodeService = require('../services/qrCodeService');
const OrderStatusService = require('../services/orderStatusService');
const OrderValidationService = require('../services/orderValidationService');

// 数据验证函数
const validateOrderData = (orderData) => {
  const errors = [];

  if (!orderData.items || !Array.isArray(orderData.items) || orderData.items.length === 0) {
    errors.push('订单商品不能为空');
  }

  if (orderData.items) {
    orderData.items.forEach((item, index) => {
      if (!item.productId) {
        errors.push(`商品${index + 1}的ID不能为空`);
      }
      if (!item.quantity || item.quantity <= 0) {
        errors.push(`商品${index + 1}的数量必须大于0`);
      }
    });
  }

  return errors;
};

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const statusMap = {
    'pending': '待处理',
    'confirmed': '已确认',
    'processing': '处理中',
    'printing': '打印中',
    'completed': '已完成',
    'cancelled': '已取消'
  };
  return statusMap[status] || status || '未知状态';
};

// 安全获取订单数据
const safeGetOrderData = (order) => {
  if (!order) return null;

  return {
    id: order.id || null,
    orderNumber: order.orderNumber || '',
    userId: order.userId || null,
    items: order.items || [],
    totalAmount: order.totalAmount || 0,
    discountAmount: order.discountAmount || 0,
    finalAmount: order.finalAmount || 0,
    pointsUsed: order.pointsUsed || 0,
    pointsEarned: order.pointsEarned || 0,
    status: order.status || 'pending',
    paymentStatus: order.paymentStatus || 'unpaid',
    paymentMethod: order.paymentMethod || null,
    deliveryInfo: order.deliveryInfo || null,
    estimatedCompletionTime: order.estimatedCompletionTime || null,
    actualCompletionTime: order.actualCompletionTime || null,
    notes: order.notes || '',
    adminNotes: order.adminNotes || '',
    files: order.files || [],
    createdAt: order.createdAt || null,
    updatedAt: order.updatedAt || null,
    User: order.User ? {
      id: order.User.id || null,
      nickname: order.User.nickname || '',
      phone: order.User.phone || ''
    } : null
  };
};

// 获取用户订单列表
router.get('/', auth, async (req, res) => {
  try {
    const { status, page = 1, limit = 10, search } = req.query;
    const where = { userId: req.user.id };

    // 验证状态参数
    const validStatuses = ['pending', 'confirmed', 'processing', 'printing', 'completed', 'cancelled'];
    if (status && !validStatuses.includes(status)) {
      return res.status(400).json({
        success: false,
        message: '无效的订单状态'
      });
    }

    if (status) {
      where.status = status;
    }

    // 处理搜索参数
    if (search && search.trim()) {
      const searchTerm = search.trim();
      where[Op.or] = [
        {
          orderNumber: {
            [Op.like]: `%${searchTerm}%`
          }
        },
        {
          items: {
            [Op.like]: `%${searchTerm}%`
          }
        }
      ];

      logger.info(`搜索订单，关键词: ${searchTerm}, 用户: ${req.user.id}`);
    }

    // 验证分页参数
    const pageNum = Math.max(1, parseInt(page));
    const limitNum = Math.min(50, Math.max(1, parseInt(limit))); // 限制每页最多50条

    const { count: total, rows: orders } = await Order.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'User',
          attributes: ['id', 'nickname', 'phone']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit: limitNum,
      offset: (pageNum - 1) * limitNum
    });

    // 安全处理订单数据
    const safeOrders = orders.map(order => safeGetOrderData(order));

    res.json({
      success: true,
      data: {
        orders: safeOrders,
        pagination: {
          current: pageNum,
          total: Math.ceil(total / limitNum),
          pageSize: limitNum,
          totalItems: total
        }
      }
    });
  } catch (error) {
    logger.error('获取订单列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取订单列表失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

// 获取所有订单（管理员）
router.get('/admin/all', auth, adminAuth, async (req, res) => {
  try {
    const { status, userId, page = 1, limit = 10, startDate, endDate, search } = req.query;
    const where = {};

    // 验证状态参数
    const validStatuses = ['pending', 'confirmed', 'processing', 'printing', 'completed', 'cancelled'];
    if (status && !validStatuses.includes(status)) {
      return res.status(400).json({
        success: false,
        message: '无效的订单状态'
      });
    }

    if (status) {
      where.status = status;
    }

    // 处理搜索参数
    if (search && search.trim()) {
      const searchTerm = search.trim();
      where[Op.or] = [
        {
          orderNumber: {
            [Op.like]: `%${searchTerm}%`
          }
        },
        {
          items: {
            [Op.like]: `%${searchTerm}%`
          }
        }
      ];

      logger.info(`管理员搜索订单，关键词: ${searchTerm}, 管理员: ${req.user.id}`);
    }

    // 验证用户ID
    if (userId) {
      const userIdNum = parseInt(userId);
      if (isNaN(userIdNum) || userIdNum <= 0) {
        return res.status(400).json({
          success: false,
          message: '无效的用户ID'
        });
      }
      where.userId = userIdNum;
    }

    // 验证日期参数
    if (startDate || endDate) {
      where.createdAt = {};
      if (startDate) {
        const start = new Date(startDate);
        if (isNaN(start.getTime())) {
          return res.status(400).json({
            success: false,
            message: '无效的开始日期'
          });
        }
        where.createdAt[Op.gte] = start;
      }
      if (endDate) {
        const end = new Date(endDate);
        if (isNaN(end.getTime())) {
          return res.status(400).json({
            success: false,
            message: '无效的结束日期'
          });
        }
        where.createdAt[Op.lte] = end;
      }
    }

    // 验证分页参数
    const pageNum = Math.max(1, parseInt(page));
    const limitNum = Math.min(100, Math.max(1, parseInt(limit))); // 管理员可以查看更多

    const { count: total, rows: orders } = await Order.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'User',
          attributes: ['id', 'nickname', 'phone']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit: limitNum,
      offset: (pageNum - 1) * limitNum
    });

    // 安全处理订单数据
    const safeOrders = orders.map(order => safeGetOrderData(order));

    res.json({
      success: true,
      data: {
        orders: safeOrders,
        pagination: {
          current: pageNum,
          total: Math.ceil(total / limitNum),
          pageSize: limitNum,
          totalItems: total
        }
      }
    });
  } catch (error) {
    logger.error('获取管理员订单列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取订单列表失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

// 获取订单详情
router.get('/:id', auth, async (req, res) => {
  try {
    const orderId = parseInt(req.params.id);

    // 验证订单ID
    if (isNaN(orderId) || orderId <= 0) {
      return res.status(400).json({
        success: false,
        message: '无效的订单ID'
      });
    }

    const where = { id: orderId };

    // 非管理员只能查看自己的订单
    if (req.user.role !== 'admin') {
      where.userId = req.user.id;
    }

    const order = await Order.findOne({
      where,
      include: [
        {
          model: User,
          as: 'User',
          attributes: ['id', 'nickname', 'phone']
        }
      ]
    });

    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    // 安全处理订单数据
    const safeOrder = safeGetOrderData(order);

    res.json({
      success: true,
      data: safeOrder
    });
  } catch (error) {
    logger.error('获取订单详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取订单详情失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

// 验证订单数据（预验证接口）
router.post('/validate', auth, async (req, res) => {
  try {
    // 获取用户信息
    const user = await User.findByPk(req.user.id);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 验证订单数据
    const validation = await OrderValidationService.validateOrderCreation(req.body, user);

    if (validation.isValid) {
      // 计算订单金额
      const amounts = OrderValidationService.calculateOrderAmount(validation.validatedData, req.body);

      // 验证金额
      const amountValidation = OrderValidationService.validateOrderAmount(amounts);
      if (!amountValidation.isValid) {
        return res.status(400).json({
          success: false,
          message: '订单金额验证失败',
          errors: amountValidation.errors
        });
      }

      res.json({
        success: true,
        message: '订单数据验证通过',
        data: {
          isValid: true,
          warnings: validation.warnings,
          amounts,
          itemCount: validation.validatedData.length,
          totalQuantity: validation.validatedData.reduce((sum, item) => sum + item.quantity, 0)
        }
      });
    } else {
      res.status(400).json({
        success: false,
        message: '订单数据验证失败',
        errors: validation.errors,
        warnings: validation.warnings
      });
    }
  } catch (error) {
    logger.error('验证订单数据失败:', error);
    res.status(500).json({
      success: false,
      message: '验证失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

// 创建订单
router.post('/', auth, async (req, res) => {
  const transaction = await Order.sequelize.transaction();

  try {
    // 获取用户信息
    const user = await User.findByPk(req.user.id, { transaction });
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 验证订单数据
    const validation = await OrderValidationService.validateOrderCreation(req.body, user);

    if (!validation.isValid) {
      return res.status(400).json({
        success: false,
        message: '订单数据验证失败',
        errors: validation.errors,
        warnings: validation.warnings
      });
    }

    // 计算订单金额
    const amounts = OrderValidationService.calculateOrderAmount(validation.validatedData, req.body);

    // 验证金额
    const amountValidation = OrderValidationService.validateOrderAmount(amounts);
    if (!amountValidation.isValid) {
      return res.status(400).json({
        success: false,
        message: '订单金额验证失败',
        errors: amountValidation.errors
      });
    }

    // 生成订单号
    const generateOrderNumber = () => {
      const date = new Date();
      const dateStr = date.getFullYear().toString() +
        (date.getMonth() + 1).toString().padStart(2, '0') +
        date.getDate().toString().padStart(2, '0');
      const randomStr = Math.random().toString(36).substr(2, 6).toUpperCase();
      return `ORD${dateStr}${randomStr}`;
    };

    // 确定支付状态和订单状态
    let paymentStatus = 'unpaid';
    let orderStatus = 'pending';

    if (req.body.paymentMethod === 'points' && amounts.pointsUsed > 0) {
      // 积分支付的订单视为已支付，直接确认
      paymentStatus = 'paid';
      orderStatus = 'confirmed';
    }

    // 创建订单
    const order = await Order.create({
      orderNumber: generateOrderNumber(), // 显式生成订单号
      userId: req.user.id,
      items: validation.validatedData,
      totalAmount: amounts.totalAmount,
      discountAmount: amounts.discountAmount,
      finalAmount: amounts.finalAmount,
      deliveryInfo: req.body.deliveryInfo,
      notes: req.body.notes || '',
      paymentMethod: req.body.paymentMethod,
      paymentStatus: paymentStatus,
      status: orderStatus,
      pointsUsed: amounts.pointsUsed,
      pointsEarned: amounts.pointsEarned
    }, { transaction });

    // 扣除使用的积分
    if (amounts.pointsUsed > 0) {
      await user.update({
        points: user.points - amounts.pointsUsed
      }, { transaction });
    }

    // 扣除商品库存
    for (const item of validation.validatedData) {
      if (item.product && typeof item.product.stock === 'number') {
        await item.product.update({
          stock: Math.max(0, item.product.stock - item.quantity)
        }, { transaction });
      }
    }

    await transaction.commit();

    // 重新获取订单数据（包含关联数据）
    const createdOrder = await Order.findByPk(order.id, {
      include: [
        {
          model: User,
          as: 'User', // 使用别名
          attributes: ['id', 'nickname', 'phone']
        }
      ]
    });

    const safeOrder = safeGetOrderData(createdOrder);

    logger.info(`订单创建成功: ${order.orderNumber}, 用户: ${req.user.id}, 金额: ${amounts.finalAmount}`);

    res.status(201).json({
      success: true,
      message: '订单创建成功',
      data: safeOrder,
      warnings: validation.warnings
    });
  } catch (error) {
    // 只有在事务还未完成时才回滚
    if (!transaction.finished) {
      await transaction.rollback();
    }
    logger.error('创建订单失败:', error);
    res.status(400).json({
      success: false,
      message: '创建订单失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

// 更新订单状态（管理员）
router.put('/:id/status', auth, adminAuth, async (req, res) => {
  try {
    const orderId = parseInt(req.params.id);
    const { status, adminNotes, estimatedCompletionTime } = req.body;

    // 验证订单ID
    if (isNaN(orderId) || orderId <= 0) {
      return res.status(400).json({
        success: false,
        message: '无效的订单ID'
      });
    }

    // 验证状态
    const validStatuses = ['pending', 'confirmed', 'processing', 'printing', 'completed', 'cancelled'];
    if (!status || !validStatuses.includes(status)) {
      return res.status(400).json({
        success: false,
        message: '无效的订单状态'
      });
    }

    // 使用状态管理服务更新订单状态
    const result = await OrderStatusService.updateOrderStatus(orderId, status, {
      adminId: req.user.id,
      adminNotes,
      estimatedCompletionTime,
      notifyUser: true
    });

    // 重新获取更新后的订单数据
    const updatedOrder = await Order.findByPk(orderId, {
      include: [
        {
          model: User,
          as: 'User',
          attributes: ['id', 'nickname', 'phone']
        }
      ]
    });

    const safeOrder = safeGetOrderData(updatedOrder);

    res.json({
      success: true,
      message: result.message,
      data: safeOrder
    });
  } catch (error) {
    logger.error('更新订单状态失败:', error);
    res.status(400).json({
      success: false,
      message: error.message || '更新订单状态失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

// 取消订单
router.put('/:id/cancel', auth, async (req, res) => {
  const transaction = await Order.sequelize.transaction();

  try {
    const orderId = parseInt(req.params.id);
    const { reason } = req.body;

    logger.info(`=== 开始取消订单流程 ===`);
    logger.info(`订单ID: ${orderId}, 用户ID: ${req.user.id}, 取消原因: ${reason}`);

    // 验证订单ID
    if (isNaN(orderId) || orderId <= 0) {
      logger.error(`无效的订单ID: ${req.params.id}`);
      return res.status(400).json({
        success: false,
        message: '无效的订单ID'
      });
    }

    const where = { id: orderId };

    // 非管理员只能取消自己的订单
    if (req.user.role !== 'admin') {
      where.userId = req.user.id;
      logger.info(`非管理员用户，限制只能取消自己的订单`);
    }

    logger.info(`查询订单条件:`, where);

    const order = await Order.findOne({
      where,
      include: [
        {
          model: User,
          as: 'User',
          attributes: ['id', 'nickname', 'phone', 'points']
        }
      ],
      transaction
    });

    if (!order) {
      logger.error(`订单不存在或无权限访问: ${orderId}`);
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    logger.info(`找到订单: ${order.orderNumber}, 状态: ${order.status}`);

    if (!['pending', 'confirmed'].includes(order.status)) {
      logger.error(`订单状态不允许取消: ${order.status}`);
      return res.status(400).json({
        success: false,
        message: '订单状态不允许取消'
      });
    }

    // 更新订单状态
    const updates = {
      status: 'cancelled',
      adminNotes: reason ? `取消原因: ${reason}` : '订单已取消'
    };

    logger.info(`更新订单状态:`, updates);
    await order.update(updates, { transaction });

    // 退还积分
    if (order.pointsUsed > 0) {
      const user = await User.findByPk(order.userId, { transaction });
      if (user) {
        const oldPoints = user.points;
        const newPoints = user.points + order.pointsUsed;

        logger.info(`退还积分: 用户${user.id}, 原积分: ${oldPoints}, 退还: ${order.pointsUsed}, 新积分: ${newPoints}`);

        await user.update({
          points: newPoints
        }, { transaction });
      } else {
        logger.error(`找不到用户: ${order.userId}`);
      }
    } else {
      logger.info(`订单未使用积分，无需退还`);
    }

    // 退还库存
    if (order.items && Array.isArray(order.items)) {
      logger.info(`开始退还库存，商品数量: ${order.items.length}`);

      for (const item of order.items) {
        const product = await Product.findByPk(item.productId, { transaction });
        if (product && product.stock !== null) {
          const oldStock = product.stock;
          const newStock = product.stock + item.quantity;

          logger.info(`退还库存: 商品${item.productId}, 原库存: ${oldStock}, 退还: ${item.quantity}, 新库存: ${newStock}`);

          await product.update({
            stock: newStock
          }, { transaction });
        } else {
          logger.warn(`商品不存在或库存为null: ${item.productId}`);
        }
      }
    } else {
      logger.info(`订单无商品项或格式错误，无需退还库存`);
    }

    await transaction.commit();
    logger.info(`事务提交成功`);

    // 重新获取更新后的订单数据
    const updatedOrder = await Order.findByPk(orderId, {
      include: [
        {
          model: User,
          as: 'User',
          attributes: ['id', 'nickname', 'phone']
        }
      ]
    });

    const safeOrder = safeGetOrderData(updatedOrder);

    logger.info(`订单取消成功: ${order.orderNumber}, 用户: ${req.user.id}`);
    logger.info(`返回数据:`, safeOrder);

    res.json({
      success: true,
      message: '订单取消成功',
      data: safeOrder
    });
  } catch (error) {
    await transaction.rollback();
    logger.error('=== 取消订单失败 ===');
    logger.error('错误详情:', error);
    logger.error('错误堆栈:', error.stack);

    res.status(500).json({
      success: false,
      message: '取消订单失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

// 获取用户订单统计
router.get('/statistics/summary', auth, async (req, res) => {
  try {
    const userId = req.user.id;

    const [
      totalOrders,
      pendingOrders,
      completedOrders,
      cancelledOrders,
      totalPoints
    ] = await Promise.all([
      Order.count({ where: { userId } }),
      Order.count({ where: { userId, status: 'pending' } }),
      Order.count({ where: { userId, status: 'completed' } }),
      Order.count({ where: { userId, status: 'cancelled' } }),
      Order.sum('pointsUsed', { where: { userId, status: 'completed' } })
    ]);

    res.json({
      success: true,
      data: {
        totalOrders: totalOrders || 0,
        pendingOrders: pendingOrders || 0,
        completedOrders: completedOrders || 0,
        cancelledOrders: cancelledOrders || 0,
        totalPoints: parseInt(totalPoints) || 0
      }
    });
  } catch (error) {
    logger.error('获取用户订单统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取统计数据失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

// 获取订单统计（管理员）
router.get('/admin/stats', auth, adminAuth, async (req, res) => {
  try {
    const { startDate, endDate } = req.query;
    const where = {};

    // 验证日期参数
    if (startDate || endDate) {
      where.createdAt = {};
      if (startDate) {
        const start = new Date(startDate);
        if (isNaN(start.getTime())) {
          return res.status(400).json({
            success: false,
            message: '无效的开始日期'
          });
        }
        where.createdAt[Op.gte] = start;
      }
      if (endDate) {
        const end = new Date(endDate);
        if (isNaN(end.getTime())) {
          return res.status(400).json({
            success: false,
            message: '无效的结束日期'
          });
        }
        where.createdAt[Op.lte] = end;
      }
    }

    const [
      totalOrders,
      pendingOrders,
      confirmedOrders,
      processingOrders,
      printingOrders,
      completedOrders,
      cancelledOrders,
      totalRevenue,
      avgOrderValue
    ] = await Promise.all([
      Order.count({ where }),
      Order.count({ where: { ...where, status: 'pending' } }),
      Order.count({ where: { ...where, status: 'confirmed' } }),
      Order.count({ where: { ...where, status: 'processing' } }),
      Order.count({ where: { ...where, status: 'printing' } }),
      Order.count({ where: { ...where, status: 'completed' } }),
      Order.count({ where: { ...where, status: 'cancelled' } }),
      Order.sum('finalAmount', { where: { ...where, status: 'completed' } }),
      Order.findOne({
        where: { ...where, status: 'completed' },
        attributes: [[Sequelize.fn('AVG', Sequelize.col('finalAmount')), 'avgValue']]
      })
    ]);

    // 获取每日订单统计（最近7天）
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);

    const dailyStats = await Order.findAll({
      where: {
        createdAt: {
          [Op.gte]: sevenDaysAgo
        }
      },
      attributes: [
        [Sequelize.fn('DATE', Sequelize.col('createdAt')), 'date'],
        [Sequelize.fn('COUNT', Sequelize.col('id')), 'count'],
        [Sequelize.fn('SUM', Sequelize.col('finalAmount')), 'revenue']
      ],
      group: [Sequelize.fn('DATE', Sequelize.col('createdAt'))],
      order: [[Sequelize.fn('DATE', Sequelize.col('createdAt')), 'ASC']]
    });

    res.json({
      success: true,
      data: {
        totalOrders: totalOrders || 0,
        pendingOrders: pendingOrders || 0,
        confirmedOrders: confirmedOrders || 0,
        processingOrders: processingOrders || 0,
        printingOrders: printingOrders || 0,
        completedOrders: completedOrders || 0,
        cancelledOrders: cancelledOrders || 0,
        totalRevenue: parseFloat(totalRevenue) || 0,
        avgOrderValue: parseFloat(avgOrderValue?.dataValues?.avgValue) || 0,
        dailyStats: dailyStats.map(stat => ({
          date: stat.dataValues.date,
          count: parseInt(stat.dataValues.count) || 0,
          revenue: parseFloat(stat.dataValues.revenue) || 0
        }))
      }
    });
  } catch (error) {
    logger.error('获取订单统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取统计数据失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

// 获取订单二维码
router.get('/:id/qrcode', auth, async (req, res) => {
  try {
    const orderId = parseInt(req.params.id);
    const { size = 256, format = 'base64' } = req.query;

    // 验证订单ID
    if (isNaN(orderId) || orderId <= 0) {
      return res.status(400).json({
        success: false,
        message: '无效的订单ID'
      });
    }

    const where = { id: orderId };

    // 非管理员只能获取自己的订单二维码
    if (req.user.role !== 'admin') {
      where.userId = req.user.id;
    }

    const order = await Order.findOne({
      where,
      include: [
        {
          model: User,
          as: 'User',
          attributes: ['id', 'nickname', 'phone']
        }
      ]
    });

    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    // 检查订单状态是否支持生成二维码
    let validStatuses = ['confirmed', 'processing', 'printing', 'completed'];

    // 对于积分支付的订单，pending状态也可以生成二维码（因为积分已扣除）
    if (order.paymentMethod === 'points' && order.paymentStatus === 'paid') {
      validStatuses.push('pending');
    }

    if (!validStatuses.includes(order.status)) {
      return res.status(400).json({
        success: false,
        message: '订单状态不支持生成二维码'
      });
    }

    // 生成二维码数据
    const qrData = qrCodeService.generateOrderQRData(order);

    if (format === 'json') {
      // 返回二维码数据
      res.json({
        success: true,
        data: {
          token: qrData.token,
          url: qrData.url,
          orderInfo: {
            id: order.id,
            orderNumber: order.orderNumber,
            status: order.status,
            finalAmount: order.finalAmount
          }
        }
      });
    } else {
      // 生成二维码图片
      const qrSize = Math.min(512, Math.max(128, parseInt(size)));
      const qrImage = await qrCodeService.generateQRCodeImage(qrData.data, { size: qrSize });

      if (format === 'image') {
        // 返回图片
        const imageBuffer = Buffer.from(qrImage, 'base64');
        res.set({
          'Content-Type': 'image/png',
          'Content-Length': imageBuffer.length,
          'Cache-Control': 'public, max-age=300' // 缓存5分钟
        });
        res.send(imageBuffer);
      } else {
        // 返回base64数据
        res.json({
          success: true,
          data: {
            image: qrImage,
            token: qrData.token,
            url: qrData.url,
            size: qrSize,
            orderInfo: {
              id: order.id,
              orderNumber: order.orderNumber,
              status: order.status,
              finalAmount: order.finalAmount
            }
          }
        });
      }
    }

    logger.info(`生成订单二维码: ${order.orderNumber}, 用户: ${req.user.id}`);
  } catch (error) {
    logger.error('生成订单二维码失败:', error);
    res.status(500).json({
      success: false,
      message: '生成二维码失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

// 验证订单二维码
router.post('/verify-qr', auth, async (req, res) => {
  try {
    const { token, qrData, orderNumber } = req.body;

    if (!token && !qrData && !orderNumber) {
      return res.status(400).json({
        success: false,
        message: '缺少二维码数据或订单号'
      });
    }

    let verifyResult;
    let order;

    if (orderNumber) {
      // 通过订单号查找
      order = await Order.findOne({
        where: { orderNumber },
        include: [
          {
            model: User,
            as: 'User',
            attributes: ['id', 'nickname', 'phone']
          }
        ]
      });

      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      verifyResult = {
        orderId: order.id,
        userId: order.userId,
        timestamp: Date.now(),
        isValid: true
      };
    } else {
      // 通过二维码验证
      if (token) {
        // 通过token验证
        verifyResult = qrCodeService.verifyOrderToken(token);
      } else {
        // 通过二维码数据验证
        verifyResult = qrCodeService.verifyOrderQRData(qrData);
      }

      if (!verifyResult) {
        return res.status(400).json({
          success: false,
          message: '无效的二维码'
        });
      }

      // 获取订单信息
      order = await Order.findByPk(verifyResult.orderId, {
        include: [
          {
            model: User,
            as: 'User',
            attributes: ['id', 'nickname', 'phone']
          }
        ]
      });

      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      // 验证用户ID匹配
      if (order.userId !== verifyResult.userId) {
        return res.status(400).json({
          success: false,
          message: '二维码与订单不匹配'
        });
      }
    }

    // 检查订单状态是否可以核销
    let validStatusesForVerification = ['confirmed', 'processing', 'printing'];

    // 对于积分支付的订单，pending状态也可以核销（因为积分已扣除）
    if (order.paymentMethod === 'points' && order.paymentStatus === 'paid') {
      validStatusesForVerification.push('pending');
    }

    if (!validStatusesForVerification.includes(order.status)) {
      return res.status(400).json({
        success: false,
        message: `订单状态为"${getOrderStatusText(order.status)}"，无法进行核销操作`
      });
    }

    const safeOrder = safeGetOrderData(order);

    res.json({
      success: true,
      message: '二维码验证成功',
      data: {
        order: safeOrder,
        verifyInfo: {
          timestamp: verifyResult.timestamp,
          isValid: verifyResult.isValid,
          canProcess: validStatusesForVerification.includes(order.status)
        }
      }
    });

    logger.info(`验证订单二维码成功: ${order.orderNumber}, 验证者: ${req.user.id}`);
  } catch (error) {
    logger.error('验证订单二维码失败:', error);
    res.status(500).json({
      success: false,
      message: '验证二维码失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

// 刷新订单二维码
router.post('/:id/refresh-qr', auth, async (req, res) => {
  try {
    const orderId = parseInt(req.params.id);

    // 验证订单ID
    if (isNaN(orderId) || orderId <= 0) {
      return res.status(400).json({
        success: false,
        message: '无效的订单ID'
      });
    }

    const where = { id: orderId };

    // 非管理员只能刷新自己的订单二维码
    if (req.user.role !== 'admin') {
      where.userId = req.user.id;
    }

    const order = await Order.findOne({ where });

    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    // 检查订单状态是否支持刷新二维码
    let validStatuses = ['confirmed', 'processing', 'printing'];

    // 对于积分支付的订单，pending状态也可以刷新二维码（因为积分已扣除）
    if (order.paymentMethod === 'points' && order.paymentStatus === 'paid') {
      validStatuses.push('pending');
    }

    if (!validStatuses.includes(order.status)) {
      return res.status(400).json({
        success: false,
        message: '订单状态不支持刷新二维码'
      });
    }

    // 生成新的二维码数据
    const qrData = qrCodeService.generateOrderQRData(order);

    res.json({
      success: true,
      message: '二维码刷新成功',
      data: {
        token: qrData.token,
        url: qrData.url,
        orderInfo: {
          id: order.id,
          orderNumber: order.orderNumber,
          status: order.status,
          finalAmount: order.finalAmount
        }
      }
    });

    logger.info(`刷新订单二维码: ${order.orderNumber}, 用户: ${req.user.id}`);
  } catch (error) {
    logger.error('刷新订单二维码失败:', error);
    res.status(500).json({
      success: false,
      message: '刷新二维码失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

// 获取订单可用的下一步状态
router.get('/:id/available-statuses', auth, adminAuth, async (req, res) => {
  try {
    const orderId = parseInt(req.params.id);

    // 验证订单ID
    if (isNaN(orderId) || orderId <= 0) {
      return res.status(400).json({
        success: false,
        message: '无效的订单ID'
      });
    }

    const order = await Order.findByPk(orderId);
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    const availableStatuses = OrderStatusService.getAvailableNextStatuses(order.status);

    res.json({
      success: true,
      data: {
        currentStatus: {
          status: order.status,
          text: OrderStatusService.getStatusText(order.status)
        },
        availableStatuses
      }
    });
  } catch (error) {
    logger.error('获取可用状态失败:', error);
    res.status(500).json({
      success: false,
      message: '获取可用状态失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

// 批量更新订单状态
router.put('/batch/status', auth, adminAuth, async (req, res) => {
  try {
    const { orderIds, status, adminNotes } = req.body;

    // 验证参数
    if (!Array.isArray(orderIds) || orderIds.length === 0) {
      return res.status(400).json({
        success: false,
        message: '订单ID列表不能为空'
      });
    }

    if (!status) {
      return res.status(400).json({
        success: false,
        message: '状态不能为空'
      });
    }

    // 验证订单ID
    const validOrderIds = orderIds.filter(id => {
      const orderId = parseInt(id);
      return !isNaN(orderId) && orderId > 0;
    });

    if (validOrderIds.length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有有效的订单ID'
      });
    }

    // 批量更新
    const result = await OrderStatusService.batchUpdateOrderStatus(validOrderIds, status, {
      adminId: req.user.id,
      adminNotes,
      notifyUser: true
    });

    res.json(result);
  } catch (error) {
    logger.error('批量更新订单状态失败:', error);
    res.status(500).json({
      success: false,
      message: '批量更新失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

// 获取订单状态统计
router.get('/admin/status-statistics', auth, adminAuth, async (req, res) => {
  try {
    const { startDate, endDate, userId } = req.query;

    const filters = {};

    // 验证日期参数
    if (startDate) {
      const start = new Date(startDate);
      if (isNaN(start.getTime())) {
        return res.status(400).json({
          success: false,
          message: '无效的开始日期'
        });
      }
      filters.startDate = start;
    }

    if (endDate) {
      const end = new Date(endDate);
      if (isNaN(end.getTime())) {
        return res.status(400).json({
          success: false,
          message: '无效的结束日期'
        });
      }
      filters.endDate = end;
    }

    // 验证用户ID
    if (userId) {
      const userIdNum = parseInt(userId);
      if (isNaN(userIdNum) || userIdNum <= 0) {
        return res.status(400).json({
          success: false,
          message: '无效的用户ID'
        });
      }
      filters.userId = userIdNum;
    }

    const result = await OrderStatusService.getOrderStatusStatistics(filters);

    res.json(result);
  } catch (error) {
    logger.error('获取订单状态统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取统计数据失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

// 处理超时订单（定时任务接口）
router.post('/admin/handle-timeout', auth, adminAuth, async (req, res) => {
  try {
    const result = await OrderStatusService.handleTimeoutOrders();

    res.json(result);
  } catch (error) {
    logger.error('处理超时订单失败:', error);
    res.status(500).json({
      success: false,
      message: '处理超时订单失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

// 检查商品库存
router.post('/check-stock', auth, async (req, res) => {
  try {
    const { items } = req.body;

    if (!Array.isArray(items) || items.length === 0) {
      return res.status(400).json({
        success: false,
        message: '商品列表不能为空'
      });
    }

    const stockInfo = [];

    for (const item of items) {
      const productId = parseInt(item.productId);
      const quantity = parseInt(item.quantity);

      if (isNaN(productId) || productId <= 0) {
        stockInfo.push({
          productId: item.productId,
          isValid: false,
          error: '无效的商品ID'
        });
        continue;
      }

      if (isNaN(quantity) || quantity <= 0) {
        stockInfo.push({
          productId,
          isValid: false,
          error: '无效的数量'
        });
        continue;
      }

      const product = await Product.findByPk(productId);
      if (!product) {
        stockInfo.push({
          productId,
          isValid: false,
          error: '商品不存在'
        });
        continue;
      }

      if (product.status !== 1) {
        stockInfo.push({
          productId,
          productName: product.name,
          isValid: false,
          error: '商品已下架'
        });
        continue;
      }

      const stockCheck = {
        productId,
        productName: product.name,
        requestedQuantity: quantity,
        isValid: true
      };

      if (product.stock !== null) {
        stockCheck.availableStock = product.stock;
        stockCheck.isStockSufficient = product.stock >= quantity;

        if (!stockCheck.isStockSufficient) {
          stockCheck.isValid = false;
          stockCheck.error = `库存不足 (可用: ${product.stock}, 需要: ${quantity})`;
        }
      } else {
        stockCheck.availableStock = null;
        stockCheck.isStockSufficient = true;
        stockCheck.note = '无库存限制';
      }

      stockInfo.push(stockCheck);
    }

    const allValid = stockInfo.every(item => item.isValid);

    res.json({
      success: true,
      data: {
        allValid,
        items: stockInfo,
        summary: {
          total: stockInfo.length,
          valid: stockInfo.filter(item => item.isValid).length,
          invalid: stockInfo.filter(item => !item.isValid).length
        }
      }
    });
  } catch (error) {
    logger.error('检查商品库存失败:', error);
    res.status(500).json({
      success: false,
      message: '检查库存失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

// 计算订单预估金额
router.post('/calculate-amount', auth, async (req, res) => {
  try {
    const { items, pointsUsed = 0, deliveryInfo } = req.body;

    if (!Array.isArray(items) || items.length === 0) {
      return res.status(400).json({
        success: false,
        message: '商品列表不能为空'
      });
    }

    // 获取用户信息
    const user = await User.findByPk(req.user.id);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 验证商品并计算价格
    let totalAmount = 0;
    const calculatedItems = [];
    const errors = [];

    for (const item of items) {
      const productId = parseInt(item.productId);
      const quantity = parseInt(item.quantity);

      if (isNaN(productId) || productId <= 0 || isNaN(quantity) || quantity <= 0) {
        errors.push(`商品 ${item.productId}: 无效的商品ID或数量`);
        continue;
      }

      const product = await Product.findByPk(productId);
      if (!product) {
        errors.push(`商品 ${productId}: 商品不存在`);
        continue;
      }

      if (product.status !== 1) {
        errors.push(`商品 ${product.name}: 商品已下架`);
        continue;
      }

      const itemTotal = parseFloat(product.price) * quantity;
      totalAmount += itemTotal;

      calculatedItems.push({
        productId,
        productName: product.name,
        quantity,
        unitPrice: parseFloat(product.price),
        totalPrice: itemTotal
      });
    }

    if (errors.length > 0) {
      return res.status(400).json({
        success: false,
        message: '商品验证失败',
        errors
      });
    }

    // 验证积分使用
    if (pointsUsed > 0 && user.points < pointsUsed) {
      return res.status(400).json({
        success: false,
        message: `积分不足 (当前: ${user.points}, 使用: ${pointsUsed})`
      });
    }

    // 计算金额
    const discountAmount = pointsUsed * 0.01;
    const deliveryFee = deliveryInfo?.deliveryFee || 0;
    const finalAmount = Math.max(0, totalAmount - discountAmount + deliveryFee);
    const pointsEarned = Math.floor(finalAmount);

    res.json({
      success: true,
      data: {
        items: calculatedItems,
        amounts: {
          totalAmount: parseFloat(totalAmount.toFixed(2)),
          discountAmount: parseFloat(discountAmount.toFixed(2)),
          deliveryFee: parseFloat(deliveryFee.toFixed(2)),
          finalAmount: parseFloat(finalAmount.toFixed(2)),
          pointsUsed,
          pointsEarned
        },
        userPoints: {
          current: user.points,
          afterOrder: user.points - pointsUsed + pointsEarned
        }
      }
    });
  } catch (error) {
    logger.error('计算订单金额失败:', error);
    res.status(500).json({
      success: false,
      message: '计算金额失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
});

module.exports = router;